package com.city.parking;

import com.city.parking.util.SharePrefUtil;
import com.city.parking.util.Utils;
import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class SettingActivity extends Activity implements OnClickListener, OnCheckedChangeListener {
	private boolean hasLogin = false;
	private Button hasLoginBtn = null;
	private UserRegister mRegister = null;
	private FeedbackAgent fb = null;
	private int type;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_setting);
		getFragmentManager().beginTransaction().replace(R.id.fragment_container, new SettingFrame()).commit();

		TextView titleTv = (TextView) findViewById(R.id.nav_title);
	    titleTv.setText("设置");
		ImageView back = (ImageView) findViewById(R.id.nav_ico_back);
		back.setOnClickListener(this);
		ImageView more = (ImageView) findViewById(R.id.nav_ico_more);
		more.setVisibility(View.GONE);
		hasLoginBtn = (Button) findViewById(R.id.login_out);
		hasLoginBtn.setOnClickListener(this);
		//Button fb = (Button) findViewById(R.id.onekey_fb);
		//fb.setOnClickListener(this);
		RadioGroup map_type = (RadioGroup) findViewById(R.id.map_type);
		map_type.setOnCheckedChangeListener(this);
		
		type = SharePrefUtil.getMapType();
		RadioButton bd = (RadioButton) findViewById(R.id.bd_rb);
		RadioButton gd = (RadioButton) findViewById(R.id.gd_rb);
		if (type == ParkingApp.BAIDU_MAP)
			bd.setChecked(true);
		else
			gd.setChecked(true);
	}
	
	private void setLoginBtnText() {
		if (hasLogin) {
			hasLoginBtn.setText("退出当前账号");
		} else {
			hasLoginBtn.setText("快速注册");
		}
	}
	
	public static class SettingFrame extends PreferenceFragment {
		private void setVersion() {
			PackageInfo pkgInfo = null;
			String verName = null;
			try {
				pkgInfo = ParkingApp.get().getPackageManager().getPackageInfo(ParkingApp.get().getPackageName(), 0);
				verName = pkgInfo.versionName;
			} catch (NameNotFoundException e) {
				verName = "";
			}
			setPreferenceSummary(R.string.pref_about_key, "v" + verName);
		}

		@Override
		public void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);

			// Load the preferences from an XML resource
			addPreferencesFromResource(R.xml.preferences);
			setVersion();
		}

		private void setPreferenceSummary(int key, String value) {
			if(value != null) {
				Preference pref = (Preference) findPreference(getString(key));
				pref.setSummary(value);
			}
		}
	}
	
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
    		if (msg.what == UserRegister.MSG_USER_REGISTER) {
				if (ParkingApp.mUid < 0) {
					hasLogin = false;
				} else {
					hasLogin = true;
				}
				setLoginBtnText();
    		}
        }
    };
	
	@Override
	protected void onResume() {
	    // TODO Auto-generated method stub
	    super.onResume();
		if (ParkingApp.mUid < 0) {
			hasLogin = false;
		} else {
			hasLogin = true;
		}
		setLoginBtnText();
	}
	
	@Override
	public void onBackPressed() {
		verifyMapType();
	};

	@Override
	public void onDestroy() {
		if (mRegister != null) {
			mRegister.onDestroy();
		}
		super.onDestroy();
	}

    public void setUpUmengFeedback() {
    	if (MainActivity.getInstance() != null) {
    		fb = MainActivity.getInstance().fb;
    		return;
    	}
    	fb = new FeedbackAgent(this);
        // check if the app developer has replied to the feedback or not.
        fb.sync();
        fb.openAudioFeedback();
        fb.openFeedbackPush();
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = fb.updateUserInfo();
            }
        }).start();
    }

    private void verifyMapType() {
    	int old =  SharePrefUtil.getMapType();
    	if (type != old) {
    		String origin = (old == ParkingApp.BAIDU_MAP ? "百度":"高德");
    		String now = (type == ParkingApp.BAIDU_MAP ? "百度":"高德");
    		
			new AlertDialog.Builder(this)
			.setTitle("请确认")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setMessage("要将"+origin+"地图变更为"+now+"地图吗？")
			.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					SharePrefUtil.setMapType(type);
					ParkingApp.mMapType = type;
					finish();
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					finish();
				}
			}).show();
    	} else {
    		finish();
    	}
    }

	@Override
    public void onClick(View v) {
	    // TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.nav_ico_back:
			verifyMapType();
			break;
		case R.id.login_out:
			if (hasLogin) {
				new AlertDialog.Builder(this)
				.setTitle("请确认")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setMessage("一定要退出当前账号吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						SharePrefUtil.logout();
						ParkingApp.mCarId = null;
						ParkingApp.mPhone = null;
						ParkingApp.mUid = -1;
						hasLogin = false;
						setLoginBtnText();
					}
				}).setNegativeButton("取消", null).show();
			} else {
				mRegister = new UserRegister(this, mHandler);
				mRegister.launchRegisterPage();
			}
			break;
		//case R.id.onekey_fb:
		//	if (fb == null) {
		//		setUpUmengFeedback();
		//	}
		//	fb.startFeedbackActivity();
		//	break;
		default:
			break;
		}
    }

	@Override
	public void onCheckedChanged(RadioGroup rg, int idx) {
		// TODO Auto-generated method stub
		switch (idx) {
		case R.id.gd_rb:
			type = ParkingApp.GAODE_MAP;
			break;
		case R.id.bd_rb:
			type = ParkingApp.BAIDU_MAP;
			break;
		}
	}
}
